/**
 * Copyright (c) 2012 Nokia Corporation.
 */

package com.nokia.example.imagescaler;

import javax.microedition.lcdui.Image;

/**
 * An image scaler using a linear interpolation algorithm.
 */
public final class LinearInterpolationScaler extends ImageScaler {
	/**
	 * From ImageScaler.
	 */
	public Image scale(final int newWidth, final int newHeight, final Image originalImage) {
		if (newWidth <= 0 || newHeight <= 0 || originalImage == null) {
			throw new IllegalArgumentException(
					"Invalid width or height or the given image is null!");
		}
		
		// Get the size and the RGB array of the original image
		final int sourceWidth = originalImage.getWidth();
		final int sourceHeight = originalImage.getHeight();
		final int[] originalRgb = new int[sourceWidth * sourceHeight];
		originalImage.getRGB(originalRgb, 0, sourceWidth, 0, 0, sourceWidth, sourceHeight);

		final int scaledRgb[] = new int[newWidth * newHeight];
		
		for (int y = 0; y < newHeight; y++) {
			final int dy = y * sourceHeight / newHeight;
			
			for (int x = 0; x < newWidth; x++) {
				final int dx = x * sourceWidth / newWidth;
				scaledRgb[(newWidth * y) + x] = originalRgb[(sourceWidth * dy) + dx];
			}
		}
		
		return Image.createRGBImage(scaledRgb, newWidth, newHeight, true);
	}

	/**
	 * From ImageScaler.
	 */
	public String type() {
		return "Linear interpolation";
	}
}
